<?php
App::uses('AppController', 'Controller');
/**
 * ChoiceQuestions Controller
 *
 * @property ChoiceQuestion $ChoiceQuestion
 */
class ChoiceQuestionsController extends AppController {

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function edit($id = null) {
		if (!$this->ChoiceQuestion->exists($id)) {
			throw new NotFoundException(__('Invalid choicequestion'));
		}

		$choiceQuestion = $this->ChoiceQuestion->findById($id);
		if (empty($choiceQuestion['ChoiceQuestionChoice'])) {
			//Provide a blank one just for kicks
			$choiceQuestion['ChoiceQuestionChoice'][] = array('label' => '');
		}
		$this->set(compact('choiceQuestion'));

		if ($this->request->is('post') || $this->request->is('put')) {
			// Replace this question's choices with the choices we got via POST
			$dataSource = $this->ChoiceQuestion->getDataSource();
			$dataSource->begin();

			$success = $this->ChoiceQuestion->ChoiceQuestionChoice->deleteAll(
				array(
					'ChoiceQuestionChoice.choicequestion_id' => $id
				)
			);

			if (!$success) {
				$dataSource->rollback();
				$this->Flash->error("There was a problem saving Choice data.");
				return;
			}

			if (!isset($this->request->data['choices'])) {
				$this->Flash->success("Successfully removed all Choices!");
				$dataSource->commit();
				return $this->redirect(array('controller' => 'Questions', 'action' => 'index', $choiceQuestion['Question']['survey_id'], '#' => sprintf('q-coll-%d', $choiceQuestion['Question']['id'])));
			}

			foreach ($this->request->data['choices'] as $newChoice) {
				$this->ChoiceQuestion->ChoiceQuestionChoice->create();
				$success = $this->ChoiceQuestion->ChoiceQuestionChoice->save( array(
					'choicequestion_id' => $id,
					'label' => $newChoice,
				));

				if (!$success) {
					$dataSource->rollback();
					$this->Flash->error("There was a problem saving Choice data.");
					return;
				}
			}
			$this->Flash->success(sprintf("Successfully saved %d Choices!", count($this->request->data['choices'])));
			$dataSource->commit();
			return $this->redirect(array('controller' => 'Questions', 'action' => 'index', $choiceQuestion['Question']['survey_id'], '#' => sprintf('q-coll-%d', $choiceQuestion['Question']['id'])));
		}

		$choiceQuestion = $this->ChoiceQuestion->findById($id);
		if (empty($choiceQuestion['ChoiceQuestionChoice'])) {
			//Provide a blank one just for kicks
			$choiceQuestion['ChoiceQuestionChoice'][] = array('label' => '');
		}
		$this->set(compact('choiceQuestion'));
	}
}
